#include <iostream>
#include <memory>
#include <signal.h>
#include <getopt.h>
#include <thread>
#include <chrono>
#include "Kv_reactor.hpp"
#include "Kv_Foundation.hpp"
#include "Kv_cluster.hpp"

using namespace std;
using namespace Redis_Foundation_Model;
using namespace Redis_Cluster_Model;
using namespace Log_Module;

// 全局服务器实例（使用智能指针避免生命周期问题）
static unique_ptr<Reactor_Module::ReactorServer> g_server = nullptr;
static unique_ptr<Reactor_Module::ClusterReactorServer> g_cluster_server = nullptr;

void signalHandler(int signal) {
    cout << "\n收到信号 " << signal << "，正在关闭服务器..." << endl;
    
    // 安全地停止服务器
    if (g_cluster_server) {
        g_cluster_server->stopCluster();
        g_cluster_server.reset();
    }
    
    if (g_server) {
        g_server->stop();
        g_server.reset();
    }
    
    // 给一点时间清理资源
    this_thread::sleep_for(chrono::milliseconds(100));
    exit(0);
}

bool initializeRedis(const string& host = "127.0.0.1", int port = 6379) {
    try {
        Redis_Foundation_Model::Redis_Client::Connection redis_conn;
        redis_conn.host = host;
        redis_conn.port = port;
        redis_conn.timeout = 1000;
        redis_conn.pool_size = 10;
        
        return Redis_Foundation_Model::Redis_Client::Initialize(redis_conn);
    } catch (const exception& e) {
        cerr << "Redis初始化异常: " << e.what() << endl;
        return false;
    }
}

shared_ptr<Redis_Cluster_Model::KvCluster> initializeCluster() {
    try {
        auto cluster = make_shared<Redis_Cluster_Model::KvCluster>("bank_cluster");
        
        // 添加多个节点进行测试
        vector<pair<string, int>> cluster_nodes = {
            {"127.0.0.1", 6379},
            {"127.0.0.1", 6380},
            {"127.0.0.1", 6381}
        };
        
        cout << "开始初始化集群节点..." << endl;
        
        for (const auto& [host, port] : cluster_nodes) {
            cout << "添加集群节点: " << host << ":" << port << endl;
            if (cluster->addNode(host, port)) {
                cout << "✓ 集群节点添加成功: " << host << ":" << port << endl;
            } else {
                cout << "✗ 集群节点添加失败: " << host << ":" << port << endl;
                // 继续尝试其他节点，不立即返回失败
            }
        }
        
        // 延迟启动集群管理
        this_thread::sleep_for(chrono::milliseconds(500));
        
        if (cluster->start()) {
            cout << "✓ 集群管理器启动成功" << endl;
            return cluster;
        } else {
            cout << "✗ 集群管理器启动失败" << endl;
            return nullptr;
        }
        
    } catch (const exception& e) {
        cerr << "集群初始化异常: " << e.what() << endl;
        return nullptr;
    }
}

void showUsage(const char* program_name) {
    cout << "用法: " << program_name << " [选项]" << endl;
    cout << "选项:" << endl;
    cout << "  -p, --port PORT      服务器端口 (默认: 8082)" << endl;
    cout << "  -c, --cluster        启用集群模式" << endl;
    cout << "  -h, --host HOST      Redis主机 (默认: 127.0.0.1)" << endl;
    cout << "  -r, --redis-port PORT Redis端口 (默认: 6379)" << endl;
    cout << "  --help               显示此帮助信息" << endl;
}


int main(int argc, char* argv[]) {
    // 设置信号处理
    signal(SIGINT, signalHandler);
    signal(SIGTERM, signalHandler);
    
    // 命令行参数
    int server_port = 8082;
    bool cluster_mode = false;
    string redis_host = "127.0.0.1";
    int redis_port = 6379;
    
    // 解析命令行参数
    static struct option long_options[] = {
        {"port", required_argument, 0, 'p'},
        {"cluster", no_argument, 0, 'c'},
        {"host", required_argument, 0, 'h'},
        {"redis-port", required_argument, 0, 'r'},
        {"help", no_argument, 0, 0},
        {0, 0, 0, 0}
    };
    
    int option_index = 0;
    int c;
    while ((c = getopt_long(argc, argv, "p:ch:r:", long_options, &option_index)) != -1) {
        switch (c) {
            case 'p':
                server_port = stoi(optarg);
                break;
            case 'c':
                cluster_mode = true;
                break;
            case 'h':
                redis_host = optarg;
                break;
            case 'r':
                redis_port = stoi(optarg);
                break;
            case 0:
                if (string(long_options[option_index].name) == "help") {
                    showUsage(argv[0]);
                    return 0;
                }
                break;
            default:
                showUsage(argv[0]);
                return 1;
        }
    }
    
    cout << "=== 银行分布式KV存储服务器 ===" << endl;
    cout << "初始化服务..." << endl;
    
    // 初始化Redis连接
    if (!initializeRedis(redis_host, redis_port)) {
        cerr << "✗ Redis连接初始化失败!" << endl;
        return 1;
    }
    cout << "✓ Redis连接初始化成功: " << redis_host << ":" << redis_port << endl;
    
    try {
        if (cluster_mode) {
            cout << "运行模式: \033[32m集群模式\033[0m" << endl;
            
            auto cluster = initializeCluster();
            if (!cluster) {
                cerr << "✗ 集群初始化失败!" << endl;
                return 1;
            }
            
            // 启动集群Reactor服务器
            g_cluster_server = make_unique<Reactor_Module::ClusterReactorServer>(cluster);
            vector<int> cluster_ports = {server_port};  // 使用配置的端口
            
            cout << "启动集群节点端口: ";
            for (int port : cluster_ports) {
                cout << port << " ";
            }
            cout << endl;
            
            if (g_cluster_server->startCluster(cluster_ports)) {
                cout << "✓ 集群服务器启动成功" << endl;
            } else {
                cerr << "✗ 集群服务器启动失败!" << endl;
                return 1;
            }
        } else {
            cout << "运行模式: \033[33m单机模式\033[0m" << endl;
            
            // 创建业务控制器
            auto biz_controller = make_shared<Business_Ctrl::MultiLevelController>();
            
            // 创建并启动Reactor服务器
            g_server = make_unique<Reactor_Module::ReactorServer>(server_port, biz_controller);
            
            cout << "启动服务器端口: " << server_port << "..." << endl;
            
            if (g_server->start()) {
                cout << "✓ 服务器启动成功" << endl;
            } else {
                cerr << "✗ 服务器启动失败!" << endl;
                return 1;
            }
        }
        
        cout << "\n服务已就绪，按 Ctrl+C 停止服务器" << endl;
        
        // 主线程等待
        while (true) {
            this_thread::sleep_for(chrono::seconds(1));
            
            // 检查服务器是否还在运行
            if (cluster_mode) {
                if (g_cluster_server && !g_cluster_server->isRunning()) {
                    cout << "集群服务器意外停止" << endl;
                    break;
                }
            } else {
                if (g_server && !g_server->isRunning()) {
                    cout << "服务器意外停止" << endl;
                    break;
                }
            }
        }
        
    } catch (const exception& e) {
        cerr << "服务器运行异常: " << e.what() << endl;
        return 1;
    }
    
    return 0;
}